package hankz.spring.beans.factory.support;

import hankz.spring.beans.BeansException;
import hankz.spring.beans.factory.config.BeanDefinition;
import java.lang.reflect.Constructor;

/**
 * @description: 实例化策略实现
 * @author: zzc
 * @modified By: zzc
 * @date: Created in 2021/11/20 16:21
 * @version:v1.0
 */
public class SimpleInstaniationStrategy implements InstantiationStrategy {

    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor constructor, Object[] args) {

        Class clazz = beanDefinition.getBeanClass();

        try {
            if (null != constructor) {
                return clazz.getDeclaredConstructor(constructor.getParameterTypes()).newInstance(args);
            } else {
                return clazz.getDeclaredConstructor().newInstance();
            }
        } catch (Exception e) {
            throw new BeansException("Failed to instantiate [" + clazz.getName() + "]");
        }

    }

}
